from PyQt5.QtCore import QUrl
from PyQt5.QtNetwork import QNetworkCookie
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWebEngineWidgets import QWebEngineView

# Qt 浏览器页面实现的代码
class Browser:
    def __init__(self, mainWindow):
        self.mainWindow = mainWindow
        self.ui = mainWindow.ui.web

        # 判断读取到的brower是否是QWebEngineView的类型，如果不是，则移除它，再添加一个QWebEngineView
        if (type(self.ui.browser) == QWidget):
            self.ui.layout_browser.removeWidget(self.ui.browser)
            self.ui.browser = QWebEngineView()
            self.ui.browser.setObjectName("browser")
            self.ui.layout_browser.addWidget(self.ui.browser)

        # 获取browser中cookie的存储对象
        self.cookieStore = self.ui.browser.page().profile().cookieStore()


    def loadData(self):
        self.ui.browser.load(QUrl(self.mainWindow.url + '/admin/welcome'))

    # 把QT登录后的cookie赋值到QWebEngineView中，使QWebEngineView也拥有访问权限
    def initCookies(self):
        # 取出 requests.session 中的 cookie，并赋值到QWebEngineView中
        qCookie = QNetworkCookie()
        qCookie.setName('session'.encode())
        qCookie.setDomain(self.mainWindow.address)
        qCookie.setValue(self.mainWindow.cookies['session'].encode())
        qCookie.setPath('/')
        self.cookieStore.setCookie(qCookie,QUrl())